import json
from control.models import *
from unit_management.models import *
import pandas as pd
from django.db import IntegrityError, transaction

# 初始化单位词头
def init_unit_prefix():

    super_admin_entity = User.objects.filter(user_account="superadmin").first()

    data_file = "files/basic_data_init_final_v2/unit_data_v2.json"
    data_content = json.load(open(data_file, "r", encoding="utf-8"))
    prefix_data = data_content["prefix"]
    prefix_entity_list = []
    for prefix_item in prefix_data:
        unit_prefix_entity = UnitPrefix(
            **{
                "prefix_name": prefix_item["prefix_name_ch"],
                "prefix_name_en": prefix_item["prefix_name_en"],
                "prefix_base": prefix_item["base"],
                "prefix_power": prefix_item["power"],
                "prefix_symbol": prefix_item["symbol"],
                "prefix_symbol_ascii": prefix_item["symbol_ascii"],
                "prefix_symbol_html": prefix_item["symbol_html"],
                "prefix_symbol_latex": prefix_item["symbol_latex"],
                "prefix_symbol_unicode": prefix_item["symbol_unicode"],
                "prefix_description": prefix_item["description"],
                "prefix_comment": prefix_item["comment"],
                "create_person": super_admin_entity,
                "modify_person": super_admin_entity,
            }
        )
        prefix_entity_list.append(unit_prefix_entity)
    UnitPrefix.objects.bulk_create(prefix_entity_list)


# 初始化基本量纲
def init_unit_basic_dimension():
    super_admin_entity = User.objects.filter(user_account="superadmin").first()

    data_file = "files/basic_data_init_final_v2/unit_data_v2.json"
    data_content = json.load(open(data_file, "r", encoding="utf-8"))
    basic_dimension_data = data_content["basic_dimension"]
    basic_dimension_entity_list = []
    for basic_dimension_item in basic_dimension_data:
        basic_dimension_entity = BasicDimension(
            **{
                "basic_dimension_name": basic_dimension_item["dimension_name_ch"],
                "basic_dimension_name_en": basic_dimension_item["dimension_name_en"],
                "basic_dimension_symbol": basic_dimension_item["symbol"],
                "basic_dimension_symbol_ascii": basic_dimension_item["symbol_ascii"],
                "basic_dimension_symbol_html": basic_dimension_item["symbol_html"],
                "basic_dimension_symbol_latex": basic_dimension_item["symbol_latex"],
                "basic_dimension_symbol_unicode": basic_dimension_item[
                    "symbol_unicode"
                ],
                "basic_dimension_description": basic_dimension_item["description"],
                "basic_dimension_description_en": basic_dimension_item["description"],
                "create_person": super_admin_entity,
                "modify_person": super_admin_entity,
            }
        )
        basic_dimension_entity_list.append(basic_dimension_entity)
    BasicDimension.objects.bulk_create(basic_dimension_entity_list)

# 初始化量纲
def init_unit_dimension():

    superscript_map = {
        '0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴',
        '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹',
        '.': '⋅', '-': '⁻', '·': '·',
    }

    up_index_list = superscript_map.values()
    
    up_index_to_normal =  {}
    for key in superscript_map:
        up_index_to_normal[superscript_map[key]]=key

    super_admin_entity = User.objects.filter(user_account="superadmin").first()
    data_file = "files/basic_data_init_final_v2/unit_data_v2.json"
    data_content = json.load(open(data_file, "r", encoding="utf-8"))
    basic_dimension_data = data_content["basic_dimension"]
    # 获取这个basic_dimension中默认单位对应entity的字典
    basic_dimension_unit_entity_map = {}
    for basic_dimension_item in basic_dimension_data:
        basic_dimension_unit_entity_map[basic_dimension_item["basic_unit"]]=BasicDimension.objects.filter(
            basic_dimension_name=basic_dimension_item["dimension_name_ch"]
        ).first()
    # 添加一个Ω
    basic_dimension_unit_entity_map["Ω"] = basic_dimension_unit_entity_map["Om"]

    # 加载excel中的数据
    # 需要修改对应的行和列数量
    unit_file_path = "files/basic_data_init_final_v2/A073. PCdata基表-1-单位表（20250403R1)-0版.xlsx"
    sheet_name = "量纲单位列表"
    df = pd.read_excel(unit_file_path,sheet_name=sheet_name,header=1,dtype=str)
    start_row = 0
    end_row = 71
    num_columns = 5
    selected_data = df.iloc[start_row:,:num_columns].fillna("")
    dimension_list = []

    # print(selected_data)
    # return 
    # 将sDimensionPhysicalSymbol转为正常的单位符号和指数
    def replace_string(s,map1):
        for char in map1:
            s = s.replace(char,map1[char])
        return s
    
    num_char_list = superscript_map.keys()
    
    for index,row  in selected_data.iterrows():
        dimension_item = {}
        dimension_item["dimension_name"] = row["sDimensionNameCN"]
        dimension_item["dimension_name_en"] = row["sDimensionName"]
        dimension_item["sei_id"] = row["nDimensionID"]
        dimension_consistent = {}
        if row["sDimensionPhysicalSymbol"]=="1":
            dimension_item["consistent"] = {}
            dimension_list.append(dimension_item)
            continue
        # print(row["sDimensionPhysicalSymbol"])
        dimension_content = row["sDimensionPhysicalSymbol"].split("·")
        for dimension1 in dimension_content:
            unit_symbol = replace_string(dimension1,up_index_to_normal)
            # 获取不在num_char_list中的
            symbol = ""
            num1 = ""
            for char1 in unit_symbol:
                if char1 not in num_char_list:
                    symbol+=char1
                else:
                    num1+=char1
            if num1 == "" :
                num1 = 1
            else:
                num1 = float(num1)
            # 如果没有，直接认为无量纲，
            if symbol not in basic_dimension_unit_entity_map:
                dimension_consistent = {}
                break
            dimension_consistent[basic_dimension_unit_entity_map[symbol]] = num1
        dimension_item["consistent"] = dimension_consistent
        dimension_list.append(dimension_item)
    
    # 进行量纲入库
    dimension_entity_list = []
    dimension_map_list = []
    try:
        with transaction.atomic():
            for dimension_item in dimension_list:
                dimension_entity = Dimension(
                    dimension_name = dimension_item["dimension_name"],
                    dimension_name_en = dimension_item["dimension_name_en"],
                    sei_id = dimension_item["sei_id"],
                    create_person = super_admin_entity,
                    modify_person = super_admin_entity
                )
                dimension_entity_list.append(dimension_entity)
                # 量纲map
                for key in dimension_item["consistent"]:
                    dimension_map_list.append(
                        DimensionMap(
                            basic_dimension = key,
                            dimension = dimension_entity,
                            power = dimension_item["consistent"][key]
                        )
                    )   
            Dimension.objects.bulk_create(dimension_entity_list)
            DimensionMap.objects.bulk_create(dimension_map_list)

            
    except IntegrityError as e:
        print(str(e))

# 初始化单位


def init_unit_unit():
    super_admin_entity = User.objects.filter(user_account="superadmin").first()

    unit_file_path = "files/basic_data_init_final_v2/A073. PCdata基表-1-单位表（20250403R1)-0版.xlsx"
    sheet_name = "单位列表"
    df = pd.read_excel(unit_file_path,sheet_name=sheet_name,header=1,dtype=str)
    start_row = 0
    end_row = 559
    num_columns = 11
    selected_data = df.iloc[start_row:,:num_columns].fillna("")
    modules = []
    current_module = []

    # print(selected_data)
    # return
    
    for index,row  in selected_data.iterrows():
        if row["nDimensionID"] == "":
            if current_module:
                modules.append(pd.DataFrame(current_module))
                current_module = []
        else:
            current_module.append(row)
    if current_module:
        modules.append(pd.DataFrame(current_module))
        
    # print(len(modules))
    # 对每个module进行入库
    unit_entity_list = []
    for module in modules:
        num = 0
        root_unit_entity = None
        dimension_entity = None
        for index,row in module.iterrows():

            if num == 0:
                # 第一个是基准单位
                dimension_entity = Dimension.objects.filter(sei_id=row["nDimensionID"]).first()
                # if dimension_entity == None:
                #     print("error",row["nDimensionID"])
                unit_entity = Unit(
                    unit_name = row["sUnitNameCN"],
                    unit_name_en = row["sUnitName"],
                    sei_id = row["nUnitIDCombine"],
                    unit_symbol = row["sUnitSymbol"],
                    dimension = dimension_entity,
                    is_show = True if row["nIsused"]=="1" else False,
                    create_person = super_admin_entity,
                    modify_person = super_admin_entity,
                )
                root_unit_entity =  unit_entity
                unit_entity_list.append(unit_entity)
            else:
                unit_entity = Unit(
                    unit_name = row["sUnitNameCN"],
                    unit_name_en = row["sUnitName"],
                    sei_id = row["nUnitIDCombine"],
                    unit_symbol = row["sUnitSymbol"],
                    dimension = dimension_entity,
                    is_show = True if row["nIsused"]=="1" else False,
                    root_unit = root_unit_entity,
                    conversion_factor = float(row["nFactor"]),
                    conversion_offset = float(row["nOffset"]),
                    create_person = super_admin_entity,
                    modify_person = super_admin_entity,
                )
                unit_entity_list.append(unit_entity)
            num+=1
    try:
        with transaction.atomic():
            Unit.objects.bulk_create(unit_entity_list)
            # raise Exception("test")
    except IntegrityError as e:
        print(str(e))

# 初始化量

def init_unit_quantity():


    super_admin_entity = User.objects.filter(user_account="superadmin").first()

    unit_file_path = "files/basic_data_init_final_v2/A073. PCdata基表-1-单位表（20250403R1)-0版.xlsx"
    sheet_name = "物理量和单位关系表"
    df = pd.read_excel(unit_file_path,sheet_name=sheet_name,header=2,dtype=str).fillna("")
    start_row = 0
    end_row = 770
    num_columns = 6
    selected_data = df.iloc[start_row:,:num_columns]
    modules = []
    current_module = []
    modules = []
    current_module = []

    # print(selected_data)
    # return 
    # num_set = set()
    for index,row  in selected_data.iterrows():
        if row["nQuantityID"] == "":
            if current_module:
                modules.append(pd.DataFrame(current_module))
                current_module = []
        else:
            # num_set.add(row["nQuantityID"])
            current_module.append(row)
    if current_module:
        # num_set.add(current_module[0]["nQuantityID"])
        modules.append(pd.DataFrame(current_module))

    # print(len(modules))
    # for i in range(0,len(modules)):
    #     print(modules[i].iloc[0,:])
    # print(selected_data)
    # for i in range(0,140):
    #     if str(i) not in num_set:
    #         print(i)
    # return 

    quantity_entity_list = []
    quantity_unit_map_list = []
    quantity_num = 0
    for module in modules:
        num = 0
        quantity_entity = None
        dimension_entity = None
        quantity_num+=1
        # print("quantity_num",quantity_num)
        # if(quantity_num==161):
        #     print("quantity_content",module)
        for index,row in module.iterrows():
            if num==0:
                unit_entity = Unit.objects.filter(sei_id = row["nUnitID"]).first()
                if unit_entity == None:
                    print("error1",row["nUnitID"],index)
                    return 
                dimension_entity = unit_entity.dimension
                quantity_entity = Quantity(
                    quantity_name=row["sQuantityNameCN"],
                    quantity_name_en = row["sQuantityName"],
                    quantity_abbreviation = row["sQuantityAbb"],
                    sei_id = row["nQuantityID"],
                    dimension = dimension_entity,
                    quantity_type = "NORMAL",
                    create_person = super_admin_entity,
                    modify_person = super_admin_entity
                )
                quantity_entity_list.append(quantity_entity)

                quantity_unit_map_list.append(
                    QuantityUnitMap(
                        quantity=quantity_entity,
                        unit = unit_entity
                    )
                )
            else:
                unit_entity = Unit.objects.filter(sei_id = row["nUnitID"]).first()
                if unit_entity == None:
                    print("error2",row["nUnitID"],index,row["sQuantityNameCN"])
                    return 
                quantity_unit_map_list.append(
                    QuantityUnitMap(
                        quantity=quantity_entity,
                        unit = unit_entity
                    )
                )
            num+=1
    try:
        with transaction.atomic():
            Quantity.objects.bulk_create(quantity_entity_list)
            QuantityUnitMap.objects.bulk_create(quantity_unit_map_list)
            # raise Exception("test")
    except IntegrityError as e:
        print(str(e))



def init_other_unit():
    super_admin_entity = User.objects.filter(user_account="superadmin").first()
    # 初始化一个叫做无量纲的量
    quantity_dimensionless_entity = Quantity.objects.filter(quantity_name="无量纲量").first()
    if quantity_dimensionless_entity is None:
        quantity_dimensionless_entity = Quantity.objects.create(
            quantity_name = "无量纲量",
            quantity_name_en = "dimensionless quantity",
            sei_id = "dimensionless",
            dimension = Dimension.objects.filter(dimension_name="无量纲").first(),
            quantity_description = "无量纲量",
            create_person = super_admin_entity,
            modify_person = super_admin_entity
        )

    # 初始化一个叫做未找到的量的量
    quantity_miss_entity = Quantity.objects.filter(quantity_name="未找到的量").first()
    if quantity_miss_entity is None:
        quantity_miss_entity = Quantity.objects.create(
            quantity_name = "未找到的量",
            quantity_name_en = "miss quantity",
            sei_id = "miss",
            dimension = Dimension.objects.filter(dimension_name="无量纲").first(),
            quantity_description = "创建量叫做未找到，标识物性绑定时没找到这个量",
            create_person = super_admin_entity,
            modify_person = super_admin_entity
        )

    # 初始化一个叫做纯度的量样本纯度使用:样本纯度
    quantity_purity_entity = Quantity.objects.filter(quantity_name="样本纯度").first()
    if quantity_purity_entity is None:
        quantity_purity_entity = Quantity.objects.create(
            quantity_name = "样本纯度",
            quantity_name_en = "sample purity",
            sei_id = "sample purity",
            dimension = Dimension.objects.filter(dimension_name="百分比").first(),
            quantity_description = "样本纯度",
            create_person = super_admin_entity,
            modify_person = super_admin_entity
        )
        # 构建样本纯度的单位集合
        unit_percent_entity = Unit.objects.filter(
            unit_symbol="%"
        ).first()
        if unit_percent_entity is not None:
            QuantityUnitMap.objects.create(
                quantity = quantity_purity_entity,
                unit=unit_percent_entity
            )








# 初始化所有单位内容


def init_unit_content():
    # init_unit_prefix()
    # init_unit_basic_dimension()
    init_unit_dimension()
    init_unit_unit()
    init_unit_quantity()
    init_other_unit()





    print("unit done")
